<template>
  <div class="goods-image">
     <!-- 放大图片位置 -->
      <div v-show="!isOutside" class="large" :style="{backgroundImage:`url(${images[currIndex]})`,...largeStyle}"></div>
     <!-- 左侧大图 -->
    <div class="middle" ref="target">
      <img :src="images[currIndex]" alt="">
      <!-- 放大镜的遮罩层 -->
      <div v-show="!isOutside" class="layer" :style="layerStyle"></div>
    </div>
    <!-- 右侧小图 -->
    <ul class="small">
      <li v-for="(img,i) in images" :key="img" :class="{active:i===currIndex}">
        <img @mouseenter="currIndex=i" :src="img" alt="">
      </li>
    </ul>
  </div>
</template>
<script>

import { ref, watch, reactive } from 'vue'
import { useMouseInElement } from '@vueuse/core'
export default {
  name: 'GoodsImage',
  props: { images: { type: Array, default: () => [] } },
  setup () {
    const currIndex = ref(0)
    const target = ref(null)
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    const layerStyle = reactive({ top: '0px', left: '0px' })
    const largeStyle = reactive({
      'background-position-x': '0px',
      'background-position-y': '0px'
    })
    // 1.监听鼠标移动，重新赋值
    watch([elementX, elementY, isOutside], () => {
      // 1.重新计算
      let top = elementY.value - 100
      let left = elementX.value - 100
      // 2.遮罩元素的位置不能移出 中图 所在范围
      if (top > 200) top = 200; if (top < 0) top = 0
      if (left > 200) left = 200; if (left < 0) left = 0
      // 3.给遮罩层重新赋值
      layerStyle.top = top + 'px'
      layerStyle.left = left + 'px'
      // 4. 给大图设置background-position的值，以移动位置的效果
      largeStyle['background-position-x'] = -2 * left + 'px'
      largeStyle['background-position-y'] = -2 * top + 'px'
    })
    return { currIndex, target, elementX, elementY, isOutside, layerStyle, largeStyle }
  }

}
</script>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    position: relative;
    cursor: move;
    background: #f5f5f5;
    .layer {
     width: 200px;
     height: 200px;
     background: rgba(0,0,0,.2);
     left: 0;
     top: 0;
     position: absolute;
    }

  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,&.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
